import { UpdatePwdFormDataProps } from '@/components/UpdatePassword/interface'
import { AppContext } from '@/pages/App/context'
import { useContext, useImperativeHandle, useRef, useState } from 'react'
import { PwdViewProps } from '../interface'

const usePwdHook = (props: PwdViewProps, ref: any) => {
	const AppData = useContext(AppContext)
	const userInfo = AppData.user
	const passwordRef = useRef<any>() //修改密码
	const oldData = {
		newPwd: '',
		currentPwd: '',
		confirmPwd: '',
	}
	const [newData, setNewData] = useState<any>({
		...oldData,
	})
	/**
	 * 暴露组件的方法
	 */
	useImperativeHandle(ref, () => ({
		/**保存数据 */
		saveData: () => {
			passwordRef.current && passwordRef.current.saveData()
		},
	}))
	const onChange = (formData: UpdatePwdFormDataProps) => {
		setNewData({
			newPwd: formData.newPwd,
			currentPwd: formData.currentPwd,
			confirmPwd: formData.confirmPwd,
		})
		props.onChange && props.onChange(formData)
	}
	const toSave = () => {
		passwordRef.current && passwordRef.current.saveData()
	}
	return { passwordRef, onChange, oldData, newData, toSave, userInfo }
}
export default usePwdHook
